<style lang='scss'>
.label-modal {
  .ivu-modal {
    top: 20px;
  }
}
</style>

<template>
	<div>
		<Form
			v-if="manual"
			:model="formdata"
			class="clearfix padding-15 bg-fff margin-bottom-15"
			ref="form"
            label-position="top"
		>
        <Row>
			<!-- <Col span="6" style="padding:0 7px;">
				<FormItem prop="shipperCountrycode" label="发货地" :rules="ruleRequire">
					<Select v-model="formdata.shipperCountrycode">
						<Option value="US">US</Option>
					</Select>
				</FormItem>
			</Col> -->
            <Col span="6" style="padding:0 7px;">
				<FormItem prop="shipperCode" label="ShipCode" :rules="ruleRequire">
                    <Input icon="ios-search" placeholder="请选择" v-model="formdata.shipperCode" @click="showShippers=true" readonly/>
				</FormItem>
			</Col>
			<Col span="6" style="padding:0 7px;">
				<FormItem prop="receiverCountrycode" label="收件地" :rules="ruleRequire">
					<Select v-model="formdata.receiverCountrycode">
						<Option value="US">US</Option>
					</Select>
				</FormItem>
			</Col>
			<!-- <Col span="6" style="padding:0 7px;">
				<FormItem prop="shipperZipcode" label="发货地邮编" :rules="ruleRequire">
					<Input v-model="formdata.shipperZipcode"/>
				</FormItem>
			</Col> -->
			<Col span="6" style="padding:0 7px;">
				<FormItem prop="receiverZipcode" label="收货地邮编" :rules="ruleRequire">
					<Input v-model="formdata.receiverZipcode"/>
				</FormItem>
			</Col>
            <Col span="6" style="padding:0 7px;">
			</Col>
            <Col span="6" style="padding:0 7px;">
				<FormItem label="地址类型">
					<Select v-model="formdata.residential">
						<Option value="1">家庭地址</Option>
                        <Option value="0">商业地址</Option>
					</Select>
				</FormItem>
			</Col>
            <Col span="6" style="padding:0 7px;">
				<FormItem label="签名服务">
					<Select v-model="formdata.deliveryConfirmation">
                        <Option v-for="(item,index) in  signServeList" :key="index" :value="item.value">{{item.label}}</Option>
                    </Select>
				</FormItem>
			</Col>
            <Col span="12" style="padding:0 7px;">
				<FormItem label="保险金额" style="width:50%;padding-right:7px">
					<Input v-model="formdata.parcelDeclareValue">
                        <template #suffix>
                            <span style="line-height:32px">USD</span>
                        </template>
                    </Input>
				</FormItem>
			</Col>
			<Col span="6" style="padding:0 7px;">
				<FormItem prop="parcelLength" label="包裹尺寸" class="label-formitem" :rules="ruleRequire">
					<InputNumber
                        class="margin-right-10"
                        placeholder="长"
						:min="1"
						v-model="formdata.parcelLength"
						@on-blur="handleSize('parcelLength',formdata.parcelLength)"
					/>
                    <InputNumber
                        class="margin-right-10"
                        placeholder="宽"
						:min="1"
						v-model="formdata.parcelWidth"
						@on-blur="handleSize('parcelWidth',formdata.parcelWidth)"
					/>
                    <InputNumber
                        class="margin-right-10"
                        placeholder="高"
						:min="1"
						v-model="formdata.parcelHeight"
						@on-blur="handleSize('parcelHeight',formdata.parcelHeight)"
					/>
					<Select v-model="formdata.parcelLengthUnit" class="width-60">
						<Option value="inch">inch</Option>
						<Option value="cm">cm</Option>
					</Select>
				</FormItem>
			</Col>
			<Col span="12">
				<FormItem prop="parcelWeight" label="包裹重量:" class="label-formitem" :rules="ruleRequire">
					<InputNumber
                    class="margin-right-10"
						:min="1"
						v-model="formdata.parcelWeight"
						@on-blur="handleSize('parcelWeight',formdata.parcelWeight)"
					/>
					<Select v-model="formdata.parcelWeightUnit" class="width-60">
						<Option value="oz">oz</Option>
						<Option value="lbs">lbs</Option>
						<Option value="g">g</Option>
					</Select>
				</FormItem>
			</Col>
			<Col class="color-error" span="24">
				<FormItem>包裹长、宽、高请输入正整数，若输入小数，则自动向上取整；包裹重量保留小数点后两位，超过两位则四舍五入保留两位</FormItem>
			</Col>
			<Col span="24" class="text-center">
				<Button type="primary" @click="submitCalculate(formdata)">测算</Button>
                <Button class="margin-left-10" @click="cancel">返回</Button>
			</Col>
        </Row>
		</Form>
		<Table
			:columns="columns"
			size="small"
			:data="data"
			ref="table"
			:loading="loading"
			@on-current-change="getCurrentRow"
			border
			highlight-row
		></Table>
		<p
			slot="footer"
			class="padding-10"
		>特别说明：测算的费用包含部分附加费,如：燃油附加费、地址附加费、超长超重附加费等；FedEx是账单制度，签收包裹后会根据官方实际账单产生额外费用，如：成人签字附加费、地址更改费等，实际费用以账单为准，计费重量是包裹毛重和体积重两者取大者，使用FedEX Ground、FedEX Home Delivery两种服务时，若加收Oversize费用时，若包裹计费重量不足90lb时，按90lb计算</p>
		<footer class="text-center padding-20" v-if="!manual&&!loading">
			<Button type="primary" @click="submit" class="width-20per" :loading="progress">获取运单</Button>
			<Button class="width-20per" @click="cancel">取消</Button>
		</footer>
        <Modal class="label-modal" v-model="showShippers" title="发货方地址" :width='800' @on-ok='confirmAddress()' @on-cancel='searchData={}'>
			<div class="width-50per margin-bottom-15 relative" @keyup.enter='getAddressList()'>
				<Input placeholder="输入发货方名称搜索" v-model="searchData.shipper" />
				<Icon class="absolute pointer" :size="22" type="ios-search" @click.native="getAddressList()" style="padding:5px 7px;right:0;top:0;background-color:#2d8cf0;color:#fff;" ></Icon>
			</div>

			<stable v-if="showShippers" :formData='{search:{EQ_active:1}}' ref="shipperTable" url='/api/jwt/spl/shipper/query' highlight-row @on-current-change='getCurrentRow1' :columns='shipperTabel' />
		</Modal>

		<!-- 全局弹框 -->
		<compModal
			v-model="modalProps.show"
			v-bind="modalProps"
            @on-close="closemodalprops"
		>
            <component :is="modalProps.component" v-bind="modalProps" v-on="modalProps.on" ></component>
        </compModal>
	</div>
</template>
<script>
import { HttpCalculatePrice, HttpPrintWaybill, HttpSaveLabel, HttpWaybill, HttpAccountOverview, HttpLabelDetail } from '@/service/api/views';
import { FSAPI } from '@/utils/assist';
import stable from './stable';
import compAlertRate from './alertrate';
export default {
    components: {
		stable,
		compAlertRate,
	},
	props: {
		manual: {
			default: true,
			type: Boolean,
		},
	},
	data() {
		return {
			modalProps:{},
			data: [],
			availableAmount: 0,
			loading: false,
			progress: false,
			currentRow: {},
			checkedId: null,
            currentShipCode: {},
			showShippers: false,
            searchData: {
				shipper: '',
				receiver: '',
			},
            shipperTabel: [
				{
					title: 'NO',
					type: 'index',
					width: 60,
				},
				{
					title: '发货方名称',
					key: 'contactName',
				},
				{
					title: '地址',
					key: 'countrycode',
					render(h, { row }) {
						let address = `${row.countrycode} ${row.state}  ${row.city}  ${row.addressLine1 || ''}`;
						return h('span', address);
					},
				},
			],
			formdata: {
				// shipperCountrycode: 'US',
				receiverCountrycode: 'US',
				parcelLength: '',
				parcelWidth: '',
				parcelHeight: '',
				parcelWeight: '',
				parcelWeightUnit: 'lbs',
				parcelLengthUnit: 'inch',
				residential: '',
			},
            signServeList: [
                {label:'NO_SIGNATURE(无需签名)',value:'NO_SIGNATURE'},
                {label:'SIGNATURE(需要签名)',value:'SIGNATURE'},
                {label:'ADULT_SIGNATURE(成人签名)',value:'ADULT_SIGNATURE'},
                {label:'INDIRECT_SIGNATURE(间接签名)',value:'INDIRECT_SIGNATURE'},
            ],
			columns: [
                {
					title: '操作',
					key: '-',
					minWidth: 200,
					render(h) {
						return h(
							'router-link',
							{
								props: {
									to: { name: 'labelAdd' },
								},
							},
							'创建运单'
						);
					},
				},
				{
					title: '运营服务',
					key: 'carrier',
					minWidth: 200,
					render(h, { row }) {
						// const serviceCode = {
						// 	FEDXG: 'Ground',
						// 	FEDSP: 'Smart Post',
                        //     FEDHD: 'Home Delivery',
                        //     UPSG: 'UPSG',
						// };
						return h('div', `${row.carrier}  ${row.serviceCode}`);
					},
				},
				// {
				// 	title: '官方价格',
				// 	key: 'originalTotalRate',
				// 	minWidth: 200,
				// 	render(h, { row }) {
				// 		const { originalTotalRate = '', currency = '' } = row;
				// 		return h('div', [originalTotalRate, '  ', currency]);
				// 	},
				// },
				{
					title: '折扣价格',
					key: 'conversionTotalRate',
					minWidth: 200,
					render:(h, { row })=>{
						// const { conversionTotalRate = '', currency = '' } = row;
						// return h('div', [conversionTotalRate, '  ', currency]);
						return <div>
							<a onClick={this.handleRate.bind(this, row)}>{row.conversionTotalRate}{row.currency}</a>
						</div>
					},
				},

			],
			ruleRequire: [
				{
					required: true,
					message: '该信息不能为空,请填写'
				},
			]
		};
	},
	created() {
		if (!this.manual) {
			this.columns = [
				{
					title: '选择',
					width: 60,
					align: 'center',
					render: (h, { row, index }) => {
						const currentRow = this.currentRow;
                        console.log(currentRow,'currentRowcurrentRow')
						return h('Radio', {
							props: {
								value: currentRow.index == index,
							},
						});
					},
				},
				{
					title: '运营服务',
					key: 'carrier',
					render(h, { row }) {
						const serviceCode = {
							FEDXG: 'Ground',
							FEDSP: 'Smart Post',
                            FEDHD: 'Home Delivery',
                            UPSG: 'UPSG',
						};
						return h('div', `${row.carrier}  ${serviceCode[row.serviceCode]}`);
					},
				},
				{
					title: '官方价格',
					key: 'originalTotalRate',
					render(h, { row }) {
						const { originalTotalRate = '', currency = '' } = row;
						return h('div', [originalTotalRate, '  ', currency]);
					},
				},
				{
					title: '折扣价格',
					key: 'conversionTotalRate',
					render(h, { row }) {
						const { conversionTotalRate = '', currency = '' } = row;
						return h('div', [conversionTotalRate, '  ', currency]);
					},
				},
				{
					title: '是否家庭地址',
					key: 'residential',
					render(h, { row }) {
						return h('div', row.residential == 1 ? '是' : '否');
					},
				},
			];
		}
		this.getFinanceData();
	},
	methods: {
		// 点击折扣价格
		handleRate(row){
			this.modalProps = {
				show:true,
				title:'查看',
				width: '600',
                component: 'compAlertRate',
				dataList:row.costItems,
				costtype:'calcul',
				showFooter:false,
			}
		},
        getCurrentRow1(currentRow) {
			this.currentShipCode = currentRow;
		},
        getAddressList() {
			this.$refs.shipperTable.updateList({
				search: { EQ_active: 1, CN_contactName: this.searchData.shipper || '' },
			});
		},
        confirmAddress() {
            const currentRow = this.currentShipCode;
            this.formdata.shipperCode = currentRow['code']
            this.formdata.shipperCountrycode = currentRow['countrycode']
            this.formdata.shipperZipcode = currentRow['zipcode']
            this.currentRow = {};
		},
		handleSize(key, val) {
			val = val || 0
			val = key === 'parcelWeight' ? val.toFixed(2) : Math.ceil(val);
			// this.$set(this.formdata, key, val)
            this.formdata[key] = val
		},
		getCurrentRow(currentRow) {
			this.currentRow = currentRow;
		},
		cancel() {
			this.$router.push({ name: 'label' });
		},
        reback(){
            this.$router.push({ name: 'shiphome' });
        },
		async getFinanceData() {
			HttpAccountOverview().then(res => {
				this.availableAmount = res.data.availableAmount;
			})
		},
		async submitCalculate(formdata) {
			if (this.manual && !await this.$refs.form.validate()) return;
			this.loading = true;
			this.currentRow = {};
			const response = await HttpCalculatePrice(formdata).catch(err => {
				this.loading = false;
				err = err.message || 'error';
				this.$Modal.error({
					title: '测算失败',
					content: `<span style=font-size:20px;>${err}</span>`,
					closable: true,
				});
			});
			if (response) {
				this.loading = false;
				this.data = (response.data || []).sort((pre, next) => {
					return pre.conversionTotalRate >= next.conversionTotalRate ? -1 : 1;
				}).map((item, index) => {
					item.index = index;
					return item;
				});
				this.formdata = { ...this.formdata, ...formdata };
			}
		},
		async submit() {
			const { carrier, serviceCode, conversionTotalRate, currency, residential } = this.currentRow || {};
			if (!carrier) return;
			this.progress = true;
			const formdata = { ...this.formdata, carrier, serviceCode, rate: conversionTotalRate, currency, residential };
			const response = await HttpSaveLabel(formdata).catch(res => {
				this.$Message.error(res.message || 'error');
				this.progress = false;
			});
			if (response) {
				const id = response.data.id;
				this.formdata.id = id;
				this.getWaybill(id);
			}
		},
		async getWaybill(id) {
			if (!id) return;
			const conversionTotalRate = this.currentRow.conversionTotalRate,
				availableAmount = this.availableAmount;
			if (availableAmount < conversionTotalRate) {
				this.$Notice.error({
					title: `预扣款失败，余额不足`,
					desc: `账户可用余额：${availableAmount} USD；请联系财务充值`,
					duration: 10
				});
				return;
			};
			HttpWaybill({ id }).then(res => {
				// clearTimeout(this._timeout);
				// this._timeout = setTimeout(() => {

				// }, 3000);
				this.$Notice.success({
					title: `预扣款成功,金额:${conversionTotalRate} USD`,
					desc: `账户可用余额：${availableAmount} USD；打印处理中...`,
					duration: 10
				});
				this.getLabelDetail(id);
			}, err => {
				this.progress = false;
				err = err.message || 'error';
				this.$Modal.error({
					title: '提示',
					content: `<span style=font-size:20px;>${err}</span>`,
					closable: true,
				});
			})
		},
		// async printLabel(id) {
		// 	const response = await HttpPrintWaybill({ ids: id }).catch(res => {
		// 		this.$Message.error(res.message || 'error');
		// 		this.progress = false;
		// 	});
		// 	if (response) {
		// 		FSAPI.printPage(response.data);
		// 		this.$router.push({ name: 'label' });
		// 	}
		// },
		async getLabelDetail(id) {
			const response = await HttpLabelDetail({ id }).catch(res => {
				this.$Message.error(res.message || 'error');
			});
			if (response) {
				FSAPI.printPage(response.data.labelUrl);
				this.$router.push({ name: "label" })
			}
		},
	},
};
</script>
